package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RRException;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.generator.entity.UserCourseEntity;
import io.renren.modules.generator.service.UserCourseService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.CourseDao;
import io.renren.modules.generator.entity.CourseEntity;
import io.renren.modules.generator.service.CourseService;
import org.springframework.transaction.annotation.Transactional;


@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseDao, CourseEntity> implements CourseService {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserCourseService userCourseService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String courseName = (String) params.get("courseName");
        IPage<CourseEntity> page = this.page(
                new Query<CourseEntity>().getPage(params),
                new QueryWrapper<CourseEntity>().like(StringUtils.isNotBlank(courseName), "course_name", courseName)
        );

        return new PageUtils(page);
    }

    @Override
    public void saveCourse(CourseEntity course) {
        if (Objects.isNull(course.getUserId())) {
            SysUserEntity userEntity = ShiroUtils.getUserEntity();
            course.setUserId(userEntity.getUserId());
            course.setNickName(userEntity.getNickName());
        } else {
            SysUserEntity sysUserEntity = sysUserService.getById(course.getUserId());
            course.setNickName(sysUserEntity.getNickName());
        }
        baseMapper.insert(course);
    }

    @Override
    public List<SysUserEntity> getAllTeacher() {
        return baseMapper.getAllTeacher();
    }

    @Override
    public void updateCourse(CourseEntity course) {
        Long userId = course.getUserId();
        if (Objects.nonNull(userId)) {
            SysUserEntity sysUserEntity = sysUserService.getById(userId);
            course.setNickName(sysUserEntity.getNickName());
        }
        baseMapper.updateById(course);

    }

    @Override
    public IPage<Map<String, Object>> studentCourse(Page<Map<String, Object>> page, Map<String, Object> params) {
        return baseMapper.studentCourse(page, params);
    }

    @Override
    public IPage<Map<String, Object>> studentList(Page<Map<String, Object>> page, Map<String, Object> params) {
        return baseMapper.studentList(page, params);
    }

    @Override
    public PageUtils teacherList(Map<String, Object> params) {
        String courseName = (String) params.get("courseName");
        IPage<CourseEntity> page = this.page(
                new Query<CourseEntity>().getPage(params),
                new QueryWrapper<CourseEntity>().eq("user_id", ShiroUtils.getUserId()).like(StringUtils.isNotBlank(courseName), "course_name", courseName)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void selectCourse(Integer id) {
        CourseEntity courseEntity = baseMapper.selectById(id);
        if (courseEntity.getCurrentNum() >= courseEntity.getTotalNum()) {
            throw new RRException("当前选课人数已满，无法选课");
        }
        Date startTime = courseEntity.getStartTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        //课程开始时间加一周
        cal.add(Calendar.DATE,7);
        Date time = cal.getTime();

        Date date = new Date();
        if(date.after(time)) {
            throw new RRException("当前课程已经开课一周，无法选课");
        }
        CourseEntity course = new CourseEntity();
        course.setCourseId(id);
        //当前选课人数加一
        course.setCurrentNum(courseEntity.getCurrentNum() + 1);
        baseMapper.updateById(course);
        //添加学生和用户的关系
        UserCourseEntity userCourseEntity = new UserCourseEntity();
        Long userId = ShiroUtils.getUserId();
        userCourseEntity.setCourseId(id);
        userCourseEntity.setUserId(userId);
        userCourseService.save(userCourseEntity);

    }

    @Override
    @Transactional
    public void exitCourse(Integer id) {
        CourseEntity courseEntity = baseMapper.selectById(id);
        Date startTime = courseEntity.getStartTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        //课程开始时间加一周
        cal.add(Calendar.DATE,7);
        Date time = cal.getTime();

        Date date = new Date();
        if(date.after(time)) {
            throw new RRException("当前课程已经开课一周，无法退课");
        }

        Long userId = ShiroUtils.getUserId();
        CourseEntity course = new CourseEntity();
        course.setCourseId(id);
        //当前选课人数减一
        course.setCurrentNum(courseEntity.getCurrentNum() - 1);
        baseMapper.updateById(course);
        //删除学生和课程之间的关系
        QueryWrapper<UserCourseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", id).eq("user_id", userId);
        userCourseService.remove(wrapper);
    }


}
